package cn.kgc.springmvc.day03.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author 课工场
 * @date 2024/11/12
 * @description springmvc中对session域对象中数据的处理方式  cookie   session
 * @SessionAttribute("info") 简化从session对象中取值的过程
 */
@RequestMapping("cs")
@Controller
public class CKSessionController {


    @RequestMapping("m1")
    public String method1(HttpSession session) {
        session.setAttribute("info", "sessionAttribute");
        return "main";
    }


    // @SessionAttribute(key)
    @RequestMapping("m2")
    public String method2(@SessionAttribute("info") String sessionValue) {
        System.out.println("sessionValue = " + sessionValue);
        return "main";
    }


    // cookie  生成在服务器端  保存在客户端的数据
    @RequestMapping("m3")
    public void method3(HttpServletRequest request, HttpServletResponse response) throws Exception {

        //  创建cookie对象
        Cookie ck1 = new Cookie("username", "root");
        Cookie ck2 = new Cookie("password", "root");

        //  设置cookie的保存路径
        ck1.setPath("/");
        ck2.setPath("/");

        // 设置cookie的生命周期
        ck1.setMaxAge(60);
        ck2.setMaxAge(120);

        // cookie需要跟随响应对象 返回到浏览器端
        response.addCookie(ck1);
        response.addCookie(ck2);

        response.sendRedirect("/mvc/main.jsp");

    }


    @RequestMapping("m4")
    public void method4(HttpServletRequest request, HttpServletResponse response) throws Exception {

        // 获取cookie
        Cookie[] cookies = request.getCookies();

        for (Cookie cookie : cookies) {
            System.out.println("cookie.getName() = " + cookie.getName());
        }

        for (Cookie cookie : cookies) {
           if ("username".equals(cookie.getName())){
               System.out.println(cookie.getValue());
           }
        }

    }

    @RequestMapping("m5")
    public String method5(@CookieValue("password") String password){

        System.out.println("password = " + password);

        return "main";

    }

}
